<?php

namespace Frieza\Modules\UserPenalty\Controllers;

use App\Http\Controllers\Controller;
use Biz\model\brand\Brand;
use Biz\model\brandIndex\BrandMsg;
use Doraemon\model\Member;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use Doraemon\cache\Queue;
use Doraemon\model\Themis\Log as mThemisLog;
use App\Pockets\GridDataModel as pGridDataModel;
use Encore\Admin\Grid;
use Encore\Admin\Widgets\Form;
use Illuminate\Support\MessageBag;
use Doraemon\tools\ImgUrl;
use Doraemon\model\AdmUserType;
use Biz\model\brand\BrandUserPenalty as mBrandUserPenalty;
use Biz\service\brand\BrandUserPenalty as sBrandUserPenalty;
use Biz\service\Userpenalty\PenaltyStrategy;
use Biz\service\BrandIndex;
use Biz\cache\brand\UserPenalty as cacheUserPenalty;
use Doraemon\service\RiskContent\RiskContentInfo;


class UserPenaltyController extends Controller
{
    const PAGE_SIZE = 20;

    const NORMAL = 0;
    const B1 = 10;
    const B2 = 9;
    const B3 = 11;
    const XL = 2;

    const STATUS_BLOCKED = 20;
    const STATUS_FROZEN = 21;
    const STATUS_STOP_COMMENT = 22;

    const QUALITY_MAP = [
        self::NORMAL => '普通',
        self::B1 => 'B1',
        self::B2 => 'B2',
        self::B3 => 'B3',
        self::XL => 'XL',
    ];
    const STATUS_MAP = [
        mThemisLog::STATUS_BLOCKED => '封禁',
        mThemisLog::STATUS_FROZEN => '冻结',
        mThemisLog::STATUS_STOP_COMMENT => '禁评'
    ];


    const ACTION_TYPE_MAP = [
        mThemisLog::ACTION_TYPE_ADD_BLOCK => '添加封禁',
        mThemisLog::ACTION_TYPE_DEL_BLOCK => '解除封禁',
        mThemisLog::ACTION_TYPE_ADD_FROZEN => '添加冻结',
        mThemisLog::ACTION_TYPE_DEL_FROZEN => '解除冻结',
        mThemisLog::ACTION_TYPE_ADD_STOP_SAYING => '添加禁言',
        mThemisLog::ACTION_TYPE_DEL_STOP_SAYING => '解除禁言',
        mThemisLog::ACTION_TYPE_ADD_COMMENT => '添加禁评',
        mThemisLog::ACTION_TYPE_DEL_COMMENT => '解除禁评',
        mThemisLog::ACTION_TYPE_ADD_B1 => '添加B1',
        mThemisLog::ACTION_TYPE_DEL_B1 => '解除B1',
        mThemisLog::ACTION_TYPE_ADD_B2 => '添加B2',
        mThemisLog::ACTION_TYPE_DEL_B2 => '解除B2',
        mThemisLog::ACTION_TYPE_ADD_B3 => '添加B3',
        mThemisLog::ACTION_TYPE_DEL_B3 => '解除B3',
    ];

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    public function brandIndex(Request $request, Content $content)
    {

        $params = $request->all();
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 20);
        $limit = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        $where = [];
        if ($params['quality']) {
            $where['quality'] = $params['quality'];
        }
        if ($params['status']) {
            if (in_array(mThemisLog::STATUS_BLOCKED, $params['status'])) {
                $where['OR']['is_forbidden'] = mBrandUserPenalty::STATUS_BLOCKED;
            }
            if (in_array(mThemisLog::STATUS_STOP_COMMENT, $params['status'])) {
                $where['OR']['is_stop_comment'] = mBrandUserPenalty::STATUS_STOP_COMMENT;
            }
            if (in_array(mThemisLog::STATUS_FROZEN, $params['status'])) {
                $where['OR']['is_frozen'] = mBrandUserPenalty::STATUS_FROZEN;
            }
        }
        if ($params['addtime']['start'] && $params['addtime']['end']) {
            $where['last_violation_time[>=]'] = strtotime($params['addtime']['start']);
            $where['last_violation_time[<=]'] = strtotime($params['addtime']['end']);
        }
        if ($request->input('uid')) {
            $where['uid'] = $request->input('uid');
        }
        $total = mBrandUserPenalty::count($where);

        $where['LIMIT'] = $limit;
        $where['ORDER'] = ['last_violation_time' => 'DESC'];
        $ThemisList = mBrandUserPenalty::getListByWhere($where);
        $result = [];
        if ($ThemisList && is_array($ThemisList)) {
            $uids = array_column($ThemisList, 'uid');
            $brandWhere['uid'] = $uids;
            $brandList = Brand::getBrandByFilter($brandWhere);
            $brandList = array_combine(array_column($brandList, 'uid'), $brandList);
            $UserTypeList = AdmUserType::getByUids($uids);
            if ($UserTypeList && is_array($UserTypeList)) {
                $UserTypeList = array_combine(array_column($UserTypeList, 'uid'), $UserTypeList);
            }
            $memberInfo = Member::getUserInfoByWhere('*', ['uid' => $uids]);
            if ($memberInfo && is_array($memberInfo)) {
                $memberInfo = array_combine(array_column($memberInfo, 'uid'), $memberInfo);
            }
            foreach ($ThemisList as $val) {
                $last_5_list = mThemisLog::getListByWhere([
                    'uid' => $val['uid'],
                    'ORDER' => ['addtime' => 'DESC'],
                    'LIMIT' => 5,
                ], ['addtime', 'remark', 'stoptime']);
                $result[] = [
                    'uid' => $val['uid'],
                    'brand_name' => $brandList[$val['uid']]['brand_name'] ?: '',
                    'nick' => $memberInfo[$val['uid']]['nick'] ?: '',
                    'Logo_url' => isset($brandList[$val['uid']]['logo']) ? ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $brandList[$val['uid']]['logo'], ImgUrl::IMAGE_SIZE_SQ_PHONE) : \Biz\service\brand\Brand::BRAND_DEFAULT_LOGO,
                    'set_time' => $brandList[$val['uid']]['created_time'],
                    'admin_id' => $val['last_admin_id'],
                    'user_type' => $UserTypeList[$val['uid']]['quality'] ?: 0,
                    'last_5_list' => $last_5_list
                ];
            }
        }
        $gridModel = new pGridDataModel($result, $total, ['perPage' => $pageSize]);
        $grid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel) {
            $grid->paginate($gridModel->getPerPage());
            $grid->disableCreateButton();
            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->column(1 / 2, function (Grid\Filter $filter) {
                    $filter->equal('uid', '品牌uid');
                    $filter->equal('status', '用户身份')->checkbox(self::STATUS_MAP);
                });
                $filter->column(1 / 2, function (Grid\Filter $filter) {
                    $filter->equal('quality', '用户身份')->checkbox(self::QUALITY_MAP);
                    $filter->between("addtime", '时间')->datetime();
                });
                $filter->expand();//默认展开
            });

            $grid->column('brand_name', '品牌名称')->display(function () {
                $html = '';
                $html .= $this->brand_name . "<br/>(" . $this->nick . ")";
                return $html;
            });
            $grid->column('uid', '品牌uid')->width(150);
            $grid->column('Logo_url', '品牌Logo')->display(function () {
                return '<img src = "' . $this->Logo_url . '" width = 80px height = 80px />';

            });
            $grid->column('set_time', '入驻时间')->display(function () {
                $html = $this->set_time;
                return $html;

            })->width(220);

            $grid->column('admin_id', '最后操作人')->display(function () {
                return $this->admin_id ? Admin::user()->find($this->admin_id)->name : '-';
            })->width(220);

            $grid->column('user_type', '当前身份')->display(function () {
                $html = self::QUALITY_MAP[$this->user_type];
                return $html;

            })->width(220);;

            $grid->column('last_5_msg', '最近5条异常')->display(function () {
                $html = '';
                foreach ($this->last_5_list as $val) {
                    $html .= date("Y-m-d H:i:s", $val['addtime']) . ":" . $val['remark'] . "<br/>";
                    if ($val['stoptime']) {
                        $html .= "  (" . date("Y-m-d H:i:s", $val['addtime']) . '-' . date("Y-m-d H:i:s", $val['stoptime']) . ")";
                    }
                    $html .= "<br/>";
                }
                return $html;

            })->width(300);
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableDelete();
                $actions->disableEdit();

                $actions->prepend("<a  class=' fa fa-bomb' href='/admin/UserPenalty/punishList/{$actions->row->uid}'>处罚列表</a>");
                $actions->prepend("<a  class=' fa fa-bug' href='/admin/UserPenalty/illegalList/{$actions->row->uid}'>违规列表</a><br/>");

                $url = "/admin/UserPenalty/brandPunish/" . $actions->row->uid;
                $actions->append('<br/><a class=" fa fa-edit" href="javascript:layer.open({
                                type: 2,
                                title: \'处罚操作\',
                                maxmin: true,
                                shadeClose: true,
                                shade: 0,
                                area: [\'800px\', \'500px\'],
                                content: \'' . $url . '\'
                            });
               ">处罚操作</a><br/>');
            });
        });
        return $content
            ->header('品牌用户惩罚列表')
            ->description(' ')
            ->breadcrumb(
                ['text' => '品牌用户惩罚列表']
            )->row($grid);
    }


    public function brandPunish(Request $request, \App\Admin\Extensions\WorkContent $content, $uid = 0)
    {
        $code = $request->input('code', 0);
        if ($code == 1) {
            $script = <<<SCRIPT
            setTimeout(function () {
                        parent.window.location.reload();
                    }, 10);
SCRIPT;
            Admin::script($script);
        }
        $fieldChane = [self::B1 => '加入B1', self::B2 => '加入B2', self::B3 => '加入B3', self::STATUS_FROZEN => "冻结", self::STATUS_STOP_COMMENT => '禁止评论', self::STATUS_BLOCKED => '封禁'];
        $form = new Form();
        $form->fieldChange('punish_status', '提醒弹窗类型', $form)
            ->options($fieldChane)
            ->callablePreCommon(function (Form $form) {
            })->callableMap([
                self::B1 => function (Form $form) {
                    $form->datetime('stoptime', '处罚截止时间')->required();

                },
                self::B2 => function (Form $form) {
                    $form->datetime('stoptime', '处罚截止时间')->required();

                },
                self::B3 => function (Form $form) {
                    $form->datetime('stoptime', '处罚截止时间')->required();

                },
                self::STATUS_STOP_COMMENT => function (Form $form) {
                    $form->datetime('stoptime', '处罚截止时间')->required();
                },
                self::STATUS_FROZEN => function (Form $form) {
                },
                self::STATUS_BLOCKED => function (Form $form) {
                },


            ]);
        $form->textarea('remark', '处罚原因')->required('不能为空');
        $form->text('preview_link', '预览链接');
        $form->action('/admin/UserPenalty/addBrandPunish/' . $uid);
        return $content
            ->row($form);
    }

    public function addBrandPunish(Request $request, $uid)
    {
        $params = $request->all();
        try {
            $stoptime = $params['stoptime'];
            if ($stoptime && strtotime($stoptime) <= time()) {
                throw new \Exception('处罚截止时间必须大于当前时间');
            }
            $punish_status = $params['punish_status'];
            if (empty($punish_status)) {
                throw new \Exception('没选择处罚方式');
            }
            $punishType = 0;
            $punishData = [];
            $quality = 0;
            $punishStatus = 0;
            $actionType = 0;
            switch ($punish_status) {
                case self::B1:
                    $punishType = PenaltyStrategy::TYPE_OPERATE_LOGO;
                    $punishData = [
                        'uid' => $uid,
                        'quality' => $punish_status,
                        'admin_id' => Admin::user()->id,
                        'admin_name' => Admin::user()->username
                    ];
                    $quality = $punish_status;
                    $actionType = mThemisLog::ACTION_TYPE_ADD_B1;
                    break;
                case self::B2:
                    $punishType = PenaltyStrategy::TYPE_OPERATE_LOGO;
                    $punishData = [
                        'uid' => $uid,
                        'quality' => $punish_status,
                        'admin_id' => Admin::user()->id,
                        'admin_name' => Admin::user()->username
                    ];
                    $quality = $punish_status;
                    $actionType = mThemisLog::ACTION_TYPE_ADD_B2;
                    break;
                case self::B3:
                    $punishType = PenaltyStrategy::TYPE_OPERATE_LOGO;
                    $punishData = [
                        'uid' => $uid,
                        'quality' => $punish_status,
                        'admin_id' => Admin::user()->id,
                        'admin_name' => Admin::user()->username
                    ];
                    $quality = $punish_status;
                    $actionType = mThemisLog::ACTION_TYPE_ADD_B3;
                    break;
                case self::STATUS_BLOCKED:
                    $punishType = PenaltyStrategy::TYPE_FORBIDDEN;
                    $punishData = [
                        'uid' => $uid,
                        'admin_id' => Admin::user()->id,
                        'admin_name' => Admin::user()->username
                    ];
                    $punishStatus = mThemisLog::STATUS_BLOCKED;
                    $actionType = mThemisLog::ACTION_TYPE_ADD_BLOCK;
                    break;
                case self::STATUS_STOP_COMMENT:
                    $punishType = PenaltyStrategy::TYPE_STOP_COMMENT;
                    $punishData = [
                        'uid' => $uid,
                        'time' => strtotime($stoptime) - time(),
                        'admin_id' => Admin::user()->id,
                        'admin_name' => Admin::user()->username
                    ];
                    $punishStatus = mThemisLog::STATUS_STOP_COMMENT;
                    $actionType = mThemisLog::ACTION_TYPE_ADD_COMMENT;
                    break;
                case self::STATUS_FROZEN:
                    $punishType = PenaltyStrategy::TYPE_FROZEN;
                    $punishData = [
                        'uid' => $uid,
                        'admin_id' => Admin::user()->id,
                        'admin_name' => Admin::user()->username,
                    ];
                    $actionType = mThemisLog::ACTION_TYPE_ADD_FROZEN;
                    $punishStatus = mThemisLog::STATUS_FROZEN;
                    break;
            }
            $result = PenaltyStrategy::addPunish($punishType, $punishData);
            if (!$result) {
                throw new \Exception('处罚执行失败');
            }
            $insertData = [];
            $insertData['uid'] = $uid;
            $insertData['member_type'] = mThemisLog::AUTH_USER_BRAND;
            $insertData['quality'] = $quality;
            $insertData['status'] = $punishStatus;
            $insertData['remark'] = $params['remark'];
            $insertData['preview_url'] = $params['preview_link'] ?: '';
            $insertData['addtime'] = time();
            $insertData['stoptime'] = $params['stoptime'] ? strtotime($params['stoptime']) : 0;
            $insertData['illegal_or_punish'] = mThemisLog::ACTION_PUNISH;
            $insertData['action_type'] = $actionType;
            $insertData['admin_id'] = Admin::user()->id;
            if (in_array($actionType, [mThemisLog::ACTION_TYPE_ADD_B1, mThemisLog::ACTION_TYPE_ADD_B2, mThemisLog::ACTION_TYPE_ADD_B3, mThemisLog::ACTION_TYPE_ADD_COMMENT])) {
                $insertData['punish_status'] = mThemisLog::IS_PUNISH;
            }
            sBrandUserPenalty::delOtherPunish($uid, $insertData);
            mThemisLog::add($insertData);
            sBrandUserPenalty::saveDataByUid($uid, $insertData);
            $brandInfo = Brand::getBrandInfoByUid($uid);
            if ($brandInfo && is_array($brandInfo) && !in_array($actionType, [mThemisLog::ACTION_TYPE_ADD_B1, mThemisLog::ACTION_TYPE_ADD_B2, mThemisLog::ACTION_TYPE_ADD_B3])) {
                //发送通知
                $msg_content = $insertData['remark'];
                if ($insertData['preview_url']) {
                    $msg_content .= " 链接地址：" . $insertData['preview_url'];
                }
                BrandIndex::writeMsg($brandInfo['id'], BrandMsg::MSG_TYPE_OVER, BrandMsg::MSG_SOURCE_H5, $msg_content);
                //发送下行消息
                Queue::insertQueue('queue/Sysmsg/Send', [
                    'msgCode' => 0,
                    'to_uid' => $uid,
                    'msgParams' => [
                        'detail' => $insertData['remark'],
                        'link' => \Biz\tools\helper\Common::formatFullScreenLink($insertData['preview_url']),
                    ]
                ], Queue::QUEUE_DORAEMON);
                $brandInfo = Brand::getBrandInfoByUid($uid);
                if ($brandInfo && is_array($brandInfo) && $actionType == mThemisLog::ACTION_TYPE_ADD_COMMENT) {
                    cacheUserPenalty::addBrand($brandInfo['id'], ['remark' => $insertData['remark'], 'link' => $insertData['preview_url']]);
                }
            }
            $success = new MessageBag([
                'title' => '保存成功'
            ]);
            return redirect("/admin/UserPenalty/brandPunish/" . $uid . "?code=1")->with(compact('success'));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '保存失败,' . $e->getMessage()
            ]);
            return back()->withInput()->with(compact('error'));
        }
    }


    public function illegalList(Request $request, Content $content, $uid)
    {
        $params = $request->all();
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 20);
        $limit = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        $where = [];
        $where['uid'] = $uid;
        $where['illegal_or_punish'] = mThemisLog::ACTION_ILLEGAL;
        $total = mThemisLog::count($where);
        $where['LIMIT'] = $limit;
        $where['ORDER'] = ['addtime' => 'DESC'];
        $ThemisList = mThemisLog::getListByWhere($where);
        if ($ThemisList && is_array($ThemisList)) {
            foreach ($ThemisList as &$val) {
                $val['addtime'] = date("Y-m-d H:i:s", $val['addtime']);
            }
        }
        $gridModel = new pGridDataModel($ThemisList, $total, ['perPage' => $pageSize]);
        $grid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel) {
            $grid->paginate($gridModel->getPerPage());
            $grid->disableCreateButton();
            $grid->disableActions();
            $grid->disableFilter();

            $grid->column('addtime', '违规时间')->width(200);
            $grid->column('remark', '违规内容记录')->width(200);;
            $grid->column('violation_type', '最近5条评论')->display(function () {
                if ($this->violation_type == 6) {
                    $comment = RiskContentInfo::getComment($this->uid);
                    $info = '';
                    if (!empty($comment)) {
                        foreach ($comment as $k => $v) {
                            $objId = $v['obj_id'];
                            $info .= "【内容id】：<a href='/admin/comment/index?search[obj_id]=$objId' target='_blank' >" . $v['obj_id'] . "</a><br/>【内容】：" . $v['comment'] . "<br/>";
                        }
                        $info .= "<br><a href='/admin/comment/index?search[uid]=$this->uid' target='_blank'>查看所有评论</a>";
                    }
                    return $info;
                }
            });
            $grid->column('admin_id', '操作人')->display(function () {
                return $this->admin_id ? Admin::user()->find($this->admin_id)->name : '系统自动检测';
            });
            $grid->disableExport();
            $grid->disableRowSelector();
        });
        $brandInfo = Brand::getBrandInfoByUid($uid);
        return $content
            ->header($brandInfo['brand_name'] . '--品牌用户违规列表')
            ->description(' ')
            ->breadcrumb(
                ['text' => '品牌用户惩罚列表']
            )->row($grid);
    }


    public function punishList(Request $request, Content $content, $uid)
    {
        $params = $request->all();
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 20);
        $limit = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        $where = [];
        $where['uid'] = $uid;
        $where['illegal_or_punish'] = mThemisLog::ACTION_PUNISH;
        $total = mThemisLog::count($where);
        $where['LIMIT'] = $limit;
        $where['ORDER'] = ['addtime' => 'DESC'];
        $ThemisList = mThemisLog::getListByWhere($where);
        if ($ThemisList && is_array($ThemisList)) {
            foreach ($ThemisList as &$val) {
                $val['addtime'] = date("Y-m-d H:i:s", $val['addtime']);
                $val['content'] = self::ACTION_TYPE_MAP[$val['action_type']];
                if ($val['illegal_or_punish'] == 2 && $val['stoptime']) {
                    $val['content'] .= "\n" . $val['addtime'] . "-" . date("Y-m-d H:i:s", $val['stoptime']);
                }
            }

        }
        $gridModel = new pGridDataModel($ThemisList, $total, ['perPage' => $pageSize]);
        $grid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel) {
            $grid->paginate($gridModel->getPerPage());
            $grid->disableCreateButton();
            $grid->disableActions();
            $grid->disableFilter();
            $grid->column('addtime', '惩罚时间')->width(200);
            $grid->column('admin_id', '操作人')->display(function () {
                return $this->admin_id ? Admin::user()->find($this->admin_id)->name : '系统自动检测';
            });
            $grid->column('content', '惩罚措施');
            $grid->column('remark', '处罚原因')->width(200);
            $grid->column('preview_url', '预览链接')->width(200);
            $grid->disableExport();
            $grid->disableRowSelector();
        });
        $brandInfo = Brand::getBrandInfoByUid($uid);
        return $content
            ->header($brandInfo['brand_name'] . '--品牌用户惩罚列表')
            ->description(' ')
            ->breadcrumb(
                ['text' => '品牌用户惩罚列表']
            )->row($grid);
    }


}
